<template>
  <div style="position: relative">
    <div class="w-form-header">
      <div class="header">
        <!-- <div class="title-box">
          <span class="title">
            {{ route.query.ID ? "修改起模通知单" : "添加起模通知单" }}</span>
        </div> -->
        <div v-if="!isViewOp">
          
          <div v-if="type == 'create'">
            <el-button type="primary" @click="saveCaogao">保存</el-button>
          </div>
          <div v-if="type == 'update'">
            <el-button type="primary" @click="preview">打印预览</el-button>
            <template v-if="userStore.userInfo.authority?.authorityId !== 1000">
                <el-button type="success" @click="subAndopenDialog">修改</el-button>
                <el-button
                  type="primary"
                  @click="print(1)"
                  v-if="detail.isDraft != 1 && detail.isMetalPrinted != 1"
                  >金打印</el-button
                >
                <el-button
                  type="primary"
                  @click="print(2)"
                  v-if="detail.isDraft != 1 && detail.isSpleenPrinted != 1"
                  >啤打印</el-button
                >
            </template>
           
           
          </div>
        </div>
        <div
          class="title-box"
          style="margin-left: auto"
          v-if="type == 'update'"
        >
          <span class="version"> 版本: {{ detail.version || "暂无" }}</span>
        </div>
      </div>
    </div>
    <div class="gva-form-box admin-content">
      <div class="form-box">
        <el-form
          :model="formData"
          ref="elFormRef"
          label-position="right"
          label-width="150px"
          v-if="type == 'create'"
        >
          <el-row :gutter="24" style="padding-right: 1.5rem">
            <el-col :span="8">
              <el-form-item
                label="款式编号："
                prop="styleNum"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'blur',
                  },
                ]"
              >
                <div
                  style="
                    width: 100%;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                  "
                >
                  <el-select
                    v-model="formData.styleNum"
                    placeholder="请选择"
                    style="min-width: 150px; margin-right: 10px; flex: 1"
                    filterable
                    remote
                    :remote-method="remoteMethodProjectStyles"
                    @change="productStylesChange"
                    :disabled="formData.status == '1'"
                  >
                    <el-option
                      v-for="item in productStylesList"
                      :key="item.styleNum"
                      :label="item.styleNum"
                      :value="item.styleNum"
                    />
                  </el-select>
                  <el-icon @click="openCreateAndEdit">
                    <Search />
                  </el-icon>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="客户要求完成日期："
                prop="customerDemandDate"
                :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-date-picker
                  v-model="formData.customerDemandDate"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DDTHH:mm:ssZ"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="PI要求完成日期：" prop="piDemandDate"  :rules="[
                  {
                    required: true,
                    message: '请选择',
                    trigger: 'blur',
                  },
                ]" >
                <el-date-picker
                  v-model="formData.piDemandDate"
                  type="date"
                  placeholder="请选择"
                  value-format="YYYY-MM-DDTHH:mm:ssZ"
                />
              </el-form-item>
            </el-col>
            <!-- <el-col :span="8">
              <el-form-item label="生产地点：">
                <el-select v-model="formData.transferOrder" :clearable="true">
                  <el-option
                    v-for="(item, index) in transferOrder"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col> -->
            <el-col :span="24">
              <el-form-item label="配件备注：" prop="accessoryNote" >
                <el-input
                  type="textarea"
                  :maxlength="200"
                  v-model="formData.accessoryNote"
                  :clearable="true"
                  placeholder="自定义填写"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 尺码-------------------------------------- -->
          <div class="gva-form-box">
            <div class="w-form-box">
              <div class="list-header">尺码</div>
              <div>
                <el-table :data="drawingLists" style="width: 100%" border>
                  <el-table-column prop="size" label="尺码" width="180">
                    <template #default="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="sizeNum" label="尺码编号">
                  </el-table-column>
                  <el-table-column prop="drawingName" label="产品规格图">
                    <template #default="scope">
                      <el-select
                        v-model="scope.row.drawingList"
                        placeholder="请选择"
                        :clearable="true"
                      >
                        <el-option
                          v-for="item in scope.row.drawingLists"
                          :key="item.ID"
                          :label="item.drawingName"
                          :value="item.fileUrl"
                        >
                        <span>{{ item.drawingName }}{{ (item.status==0 ? '(草稿)' : item.status==1?'(完成)' : item.status==2 ? '(审批中)' : '') }}</span>
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="300">
                    <template #default="{ row, $index }">
                      <!-- <el-space wrap>
                        <a
                          v-if="row.drawingList"
                          :href="`dayuer-cadopen:${path1}${row.drawingList}?ID=${row.ID}&action=view&X-Token=${xToken}`"
                          >查看</a
                        >
                      </el-space> -->
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </el-form>
        <div v-else>
          <div class="table-form">
            <div class="table-title">
              <el-icon style="transform: translateY(2px)">
                <Discount />
              </el-icon>
              基本资料
            </div>
            <el-descriptions title=" " border :column="4">
              <el-descriptions-item label="起模单编号">{{
                detail.noticeNum
              }}</el-descriptions-item>
              <el-descriptions-item label="客户款号">{{
                detail.customerStyleNum
              }}</el-descriptions-item>
              <el-descriptions-item label="片弧弯">{{
                detail.sheetArcBend
              }}</el-descriptions-item>
              <el-descriptions-item label="工程师组长">
                {{ detail.peLeader }}</el-descriptions-item
              >
              <el-descriptions-item label="款式编号">
                {{ detail.styleNum }}</el-descriptions-item
              >
              <el-descriptions-item label="客户要求完成">
                <el-date-picker
                  v-model="formData.customerDemandDate"
                  type="date"
                  placeholder="请选择"
                  disabled
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-descriptions-item>
              <el-descriptions-item label="本厂架倾角度">
                {{ detail.localTiltAngle }}</el-descriptions-item
              >
              <el-descriptions-item label="设计师">
                {{ detail.designer }}</el-descriptions-item
              >
              <el-descriptions-item label="本厂款号">
                {{ detail.localStyleNum }}</el-descriptions-item
              >
              <el-descriptions-item label="PI要求完成日期">
                <el-date-picker
                  v-model="formData.piDemandDate"
                  type="date"
                  placeholder="请选择"
                  disabled
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-descriptions-item>
              <el-descriptions-item label="客户架倾角度">
                {{ detail.customerTiltAngle }}</el-descriptions-item
              >
              <el-descriptions-item label="制作部門">
                <!-- <el-select v-model="formData.transferOrder" disabled :clearable="true">
                  <el-option
                    v-for="(item, index) in transferOrder"
                    :key="index"
                    :label="item"
                    :value="item"
                  ></el-option>
                </el-select> -->

                <el-select
                :disabled="isViewOp || !btnAuth['制作部门']"
                v-model="formData.productionDepartment"
                @change="productionDepartmentChange"
                :clearable="false"
                style="width:100%;"
              >
              
                <el-option
                  v-for="item in productionDepartmentList"
                  :key="item.ID"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
              </el-descriptions-item>
              <el-descriptions-item label="SBU">
                {{ detail.sbuNum }}</el-descriptions-item
              >
              <el-descriptions-item label="系列">
                {{ detail.series }}</el-descriptions-item
              >
              <el-descriptions-item label="创建时间">
                {{ formatDate(detail.CreatedAt) }}</el-descriptions-item
              >
              <el-descriptions-item label="创建人">
                <span v-if="detail.createdUser && detail.createdUser.nickName">
                  {{ detail.createdUser.nickName }}
                </span>
                <span v-else>{{ formData.createUser }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="客户编号">
                {{ detail.cumstomerNum }}</el-descriptions-item
              >
              <el-descriptions-item label="镜架材质">
                {{ detail.frameMaterials }}</el-descriptions-item
              >
              <el-descriptions-item label="更新时间">
                {{ formatDate(detail.UpdatedAt) }}</el-descriptions-item
              >
              <el-descriptions-item label="更新人">
                <span v-if="detail.updatedUser && detail.updatedUser.nickName">
                  {{ detail.updatedUser.nickName }}
                </span>
                <span v-else>{{ detail.updateUser }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="第一版本创建时间">
                <span >
                  {{formatDate(detail.FirstCreatedAt )=="1-01-01" ? '' : formatDate(detail.FirstCreatedAt ) }}
                </span>
               
              </el-descriptions-item>
            </el-descriptions>
            <el-form-item
              label="配件备注："
              style="display: flex; align-items: center; width: 100%;margin-top: 20px;"
            >
              <el-input
                type="textarea"
                :maxlength="200"
                v-model="formData.accessoryNote"
                :clearable="true"
                placeholder="自定义填写"
                disabled
              />
            </el-form-item>
            <!-- <el-form-item :label="`制作部門：`" style="margin-top: 10px;width:100%;">
            
            </el-form-item> -->
          </div>

          <div class="gva-form-box">
            <div class="w-form-box">
              <div class="list-header">模房复期</div>
              <div>
                <LTable
                  :columns="boardMakingColumns"
                  :tableData="boardMakingTalbeData"
                  :pagination="false"
                  :selection="false"
                  :showConfig="false"
                  :tableProps="{}"
                >
                  <template #action>
                    <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
                      <el-button
                        type="primary"
                        icon="plus"
                        :disabled="isViewOp"
                        @click="addBoardMaking"
                        >添加</el-button
                      >
                    </div>
                  </template>
                  <template #event>
                    <el-table-column
                      align="left"
                      label="操作"
                      fixed="right"
                      min-width="260"
                    >
                      <template #default="{ row }">
                        <el-button
                          v-if="row.status === '审核中'"
                          type="primary"
                          link
                          class="table-button"
                          @click="auditBoardMaking(row)"
                        >
                          <el-icon style="margin-right: 5px">
                            <InfoFilled />
                          </el-icon>
                          审核
                        </el-button>
                      </template>
                    </el-table-column>
                  </template>
                  <template #status="{ row }">
                    <span v-if="row.status === '审核中'">审核中</span>
                    <span v-if="row.status === '通过'" style="color: #67c23a"
                      >通过</span
                    >
                    <span v-if="row.status === '拒绝'" style="color: #f56c6c"
                      >拒绝</span
                    >
                  </template>
                </LTable>
              </div>
            </div>
          </div>

          <div class="gva-form-box">
            <div class="w-form-box">
              <div class="list-header">尺码</div>
              <div>
                <el-table :data="drawingLists" style="width: 100%" border>
                  <el-table-column prop="size" label="尺码" width="180">
                    <template #default="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="sizeNum" label="尺码编号">
                  </el-table-column>
                  <el-table-column prop="drawingName" label="产品规格图">
                    <template #default="scope">
                      <span v-if="scope.row.drawingName">{{
                        scope.row.drawingName
                      }}</span>
                      <span v-else>{{
                        scope.row.drawingList.split("/")[
                          scope.row.drawingList.split("/").length - 1
                        ]
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="300">
                    <template #default="{ row, $index }">
                      <!-- <el-space wrap>
                        <a
                          v-if="row.drawingList"
                          :href="`dayuer-cadopen:${path1}${row.drawingList}?ID=${row.ID}&action=view&X-Token=${xToken}`"
                          >查看</a
                        >
                      </el-space> -->
                      <a
                        v-if="row.drawingList"
                        href="javascript:void(0)"
                        class="image-icon"
                        @click="downloadFile(row)"
                        >下载图纸</a
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>

          <div class="gva-form-box">
            <div class="w-form-box" >
              <div class="list-header">
                模具及物料清单
                <el-button
                  type="warning"
                  v-if="userStore.userInfo.authority?.authorityId !== 1000"
                  :disabled="!selectList.length"
                  @click="changeStatus('暂停')"
                  >暂停配件起模</el-button
                >
                <el-button
                  type="danger"
                  v-if="userStore.userInfo.authority?.authorityId !== 1000"
                  :disabled="!selectList.length"
                  @click="changeStatus('终止')"
                  >终止配件起模</el-button
                >
                <el-button
                  type="success"
                  v-if="userStore.userInfo.authority?.authorityId !== 1000"
                  :disabled="!selectList.length"
                  @click="changeStatus('正常')"
                  >恢复正常</el-button
                >
              </div>
              <div>
                <el-table
                  :data="detail.moldmaterialLists"
                  style="width: 100%"
                  border
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column prop="status" label="状态" width="150">
                    <template #default="scope">
                      <el-select
                        placeholder="请选择"
                        :modelValue="scope.row.status"
                        @update:modelValue="statusChange(scope.row, $event)"
                        :disabled="userStore.userInfo.authority?.authorityId == 1000"
                      >
                        <el-option label="正常" value="正常" />
                        <el-option label="暂停" value="暂停" />
                        <el-option label="终止" value="终止" />
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column label="配件名称" prop="accessoryName">
                  </el-table-column>
                  <el-table-column label="配件编号" prop="componentNum">
                  </el-table-column>
                  <el-table-column prop="accessoryMaterials" label="配件用料">
                  </el-table-column>
                  <el-table-column
                    prop="metalOrSpleen"
                    label="金/啤"
                    width="200"
                  >
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>

          <div class="gva-form-box">
            <div class="w-form-box">
              <div class="list-header">历史修改备注</div>
              <div>
                <el-table
                  :data="detail.moldStartNoticeModifyNotes"
                  style="width: 100%"
                  border
                >
                  <el-table-column prop="" label="序号" width="80">
                    <template #default="scope">
                      {{ scope.$index + 1 }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="content"
                    label="更改内容"
                    min-width="200"
                  >
                  </el-table-column>
                  <el-table-column
                    prop="reason"
                    label="更改原因"
                    min-width="200"
                  >
                  </el-table-column>
                  <el-table-column prop="detail" label="详细说明">
                  </el-table-column>
                  <el-table-column
                    prop="CreatedAt"
                    label="更新时间"
                    width="180"
                  >
                    <template #default="scope">
                      {{ formatDate(scope.row.CreatedAt) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="updateUser" label="更新人" width="100">
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 生成本场颜色描述弹窗 -->
    <el-dialog v-model="subDialogFormVisible" title="添加修改备注" width="800">
      <el-form :model="subForm" :rules="subFormRules">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="内容分类：" prop="contentCate">
              <el-checkbox-group v-model="subForm.contentCate">
                <el-checkbox
                  v-for="item in contentCateList"
                  :label="item.label"
                  :value="item.value"
                  style="display: block"
                />
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="原因分类：" prop="reasonCate">
              <el-checkbox-group v-model="subForm.reasonCate">
                <el-checkbox
                  v-for="item in reasonCateList"
                  :label="item.label"
                  :value="item.value"
                  style="display: block"
                />
              </el-checkbox-group>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="详细说明" prop="materialNum">
              <el-input
                type="textarea"
                :maxlength="200"
                :clearable="true"
                placeholder="自定义填写"
                v-model="subForm.remark"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="subDialogCel">取消</el-button>
          <el-button type="primary" @click="saveByRole"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 模房复期 -->
    <!-- 添加模房付期 -->
    <el-dialog
      v-if="boardMakingVisible"
      v-model="boardMakingVisible"
      destroy-on-close
      width="50%"
      title="模房复期"
    >
      <el-form ref="boardMakingFormRef" :model="boardMakingForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="复期日期：">
              <el-date-picker
                v-model="boardMakingForm.deliveryDate"
                type="date"
                value-format="YYYY-MM-DDTHH:mm:ssZ"
                placeholder="选择日期"
                :clearable="true"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细说明：" style="width: 100%">
              <textarea
                v-model="boardMakingForm.detailDescription"
                :rows="5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addBoardMakingSubmit"
            >确定</el-button
          >
          <el-button
            @click="(boardMakingForm = {}), (boardMakingVisible = false)"
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <!-- 审核模房付期 -->
    <el-dialog
      v-if="auditBoardMakingVisible"
      v-model="auditBoardMakingVisible"
      destroy-on-close
      width="50%"
      title="模房复期"
    >
      <el-form ref="auditBoardMakingFormRef" :model="auditBoardMakingForm">
        <el-row>
          <el-col :span="24">
            <el-form-item label="付期日期：">
              <el-radio-group v-model="auditBoardMakingForm.status">
                <el-radio
                  value="通过"
                  size="large"
                  border
                  style="color: #67c23a"
                  >通过</el-radio
                >
                <el-radio
                  value="拒绝"
                  size="large"
                  border
                  style="color: #f56c6c"
                  >拒绝</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细说明：" style="width: 100%">
              <textarea
                v-model="auditBoardMakingForm.auditDescription"
                :rows="5"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="auditBoardMakingSubmit"
            >确定</el-button
          >
          <el-button
            @click="
              (auditBoardMakingForm = {}), (auditBoardMakingVisible = false)
            "
            >取消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <styleNumSearch
      v-if="editReasonDialogShow"
      @closeDialog="closeDialog"
      searchType="masterBom"
      @selectStyleNum="selectStyleNum"
    ></styleNumSearch>

    <!-- 打印预览弹窗 -->
    <div class="preview-box" v-if="previewDialogShow">
      <div id="myPrint">
        <div class="one-box">
          <div>{{ dayjs().format("YYYY-MM-DD HH:mm:ss") }}</div>
          <div style="text-align: center">起模通知单</div>
          <div style="margin-right: 10px">
            版本:{{ detail.version || "暂无" }}
          </div>
        </div>

        <div class="content-box">
          <div class="title">基本資料</div>
          <div class="content">
            <el-descriptions class="margin-top" title="" :column="4">
              <el-descriptions-item label="起模單編號">
                {{ detail.noticeNum }}
              </el-descriptions-item>

              <el-descriptions-item label="本廠款號：">
                {{ detail.localStyleNum }}
              </el-descriptions-item>

              <el-descriptions-item label="客款號：">
                {{ detail.customerStyleNum }}
              </el-descriptions-item>

              <el-descriptions-item label="架類材質：">
                {{ detail.frameMaterials }}
              </el-descriptions-item>

              <el-descriptions-item label="客户要求完成期：">
                {{ formatDate(formData.customerDemandDate) }}
              </el-descriptions-item>

              <el-descriptions-item label="PI要求完成期：">
                {{ formatDate(formData.piDemandDate) }}
              </el-descriptions-item>

              <el-descriptions-item label="系列：">
                {{ detail.series }}
              </el-descriptions-item>

              <el-descriptions-item label="SBU：">
                {{ detail.sbuNum }}
              </el-descriptions-item>

              <el-descriptions-item label="客戶編號：">
                {{ detail.cumstomerNum }}
              </el-descriptions-item>

              <el-descriptions-item label="片弧彎：">
                {{ detail.sheetArcBend }}
              </el-descriptions-item>

              <el-descriptions-item label="款式編號：">
                {{ detail.styleNum }}
              </el-descriptions-item>

              <el-descriptions-item label="客戶架傾角（度）：">
                {{ detail.customerTiltAngle }}
              </el-descriptions-item>

              <el-descriptions-item label="本廠架傾角（度）：">
                {{ detail.localTiltAngle }}
              </el-descriptions-item>

              <el-descriptions-item label="工程師組長：">
                {{ detail.peLeader }}
              </el-descriptions-item>

              <el-descriptions-item label="設計師：">
                {{ detail.designer }}
              </el-descriptions-item>

              <el-descriptions-item label=""> </el-descriptions-item>

              <el-descriptions-item label="設計規格圖：">
                {{ drawingLists.map((item) => item.drawingList).join(",") }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <div class="content-box">
          <div class="title">模具及物料清單</div>
          <div class="content" style="padding-bottom: 20px; border-bottom: 0">
            <div class="myTable-head">
              <div>配件名稱</div>
              <div>配件編號</div>
              <div>配件用料</div>
            </div>
            <div
              class="myTable-content"
              v-for="(item, index) in detail.moldmaterialLists"
              :key="index"
            >
              <div>
                {{ item.accessoryName }}
              </div>
              <div>
                {{ item.componentNum }}
              </div>
              <div>
                {{ item.accessoryMaterials }}
              </div>
            </div>
          </div>
        </div>
      </div>

      <div style="text-align: center; margin-top: 100px">
        <el-button type="primary" @click="printNotice">打印</el-button>
        <el-button @click="closePreview">关闭</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getProductStylesList } from "@/api/plmProductStyles";
import { getProductSpecSizeList } from "@/api/productSpecSize";
import { getDdmsSpecDrawingListList } from "@/api/ddmsSpecDrawingList";
import {
  createMoldStartNotice,
  findMoldStartNotice,
  setMetalSpleenPrint,
  updateMoldStartNotice,
  createMoldStartNoticeMoldHouse,
  getMoldStartNoticeMoldHouseList,
  updateMoldStartNoticeMoldHouse,
  updateMoldStartNoticeDepartment
} from "@/api/plmMoldStartNotice";
import { findProductStyles } from "@/api/plmProductStyles";
import LTable from "@/components/LTable/LTable.vue";
import { emitter } from "@/utils/bus.js";
import { updateMoldStartNoticeMoldmaterialList } from "@/api/moldStartNoticeMoldmaterialList";
import { getDict } from "@/utils/dictionary";
import { ElMessage, ElMessageBox } from "element-plus";
import { formatDate } from "@/utils/format";
import { downloadFilePost } from "@/api/comment.js";
import styleNumSearch from "@/components/styleNumSearch/styleNumSearch.vue";
import dayjs from "dayjs";
import print from "print-js";
import { useBtnAuth } from "@/utils/btnAuth";
import { useUserStore } from "@/pinia/modules/user";
export default {
  name: "moldStartNoticeAdd",
  components: {
    LTable,
    styleNumSearch,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const btnAuth = useBtnAuth();
    const userStore = useUserStore();
    const state = reactive({
      formData: {
        styleNum: "",
        customerDemandDate: undefined,
        piDemandDate: undefined,
        accessoryNote: undefined,
        // transferOrder: undefined,
      },
      productStylesList: [], //款式列表
      type: "create",
      drawingLists: [],
      detail: {},
      subDialogFormVisible: false,
      subForm: {
        reasonCate: undefined,
        contentCate: undefined,
        remark: "",
      },
      wuliaoList: [],
      subFormRules: {
        reasonCate: [{ required: true, message: "请选择", trigger: "blur" }],
        contentCate: [{ required: true, message: "请选择", trigger: "blur" }],
      },
      reasonCateList: [], //原因分类
      contentCateList: [], //内容分类
      selectList: [], //模具及物料清单选中项
      allowClick: true,
      transferOrder: [],
      editReasonDialogShow: false,
      previewDialogShow: false,
      isViewOp: false,
      productionDepartmentList:[],
    });
    const path1 = ref(import.meta.env.VITE_BASE_API + "/");
    const xToken = localStorage.getItem("token");
    // 初始化方法
    const init = async () => {
      // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
      const {
        query: { ID, version, noticeNum, isView, isBigVersion },
      } = route;
      if (version && isBigVersion != 1) {
        state.isViewOp = true;
      }
      if (ID) {
        state.type = "update";
        const res = await findMoldStartNotice({ ID: ID, version, noticeNum });
        if (res.code === 0) {
          state.detail = res.data.remoldStartNotice;
          state.formData.styleNum = state.detail.styleNum;
          state.drawingLists = state.detail.drawingLists;
          if (state.detail.customerDemandDate) {
            state.formData.customerDemandDate = state.detail.customerDemandDate;
          }
          if (state.detail.piDemandDate) {
            state.formData.piDemandDate = state.detail.piDemandDate;
          }
          if (state.detail.accessoryNote) {
            state.formData.accessoryNote = state.detail.accessoryNote;
          }
          if (state.detail.transferOrder) {
            // state.formData.transferOrder = state.detail.transferOrder;
          }
          productStylesChange(state.detail.styleNum);
          // 获取板房付期数据
          getMoldStartNoticeMoldHouseList({
            noticeNum: state.detail.noticeNum,
          }).then((res) => {
            if (res.code === 0) {
              boardMakingTalbeData.value = res.data.list;
            }
          });
          // 获取原因分类
          getDict("reasonCate").then((res) => {
            state.reasonCateList = res;
          });

          // 获取内容分类
          getDict("contentCate").then((res) => {
            state.contentCateList = res;
          });

          // 获取制作部门
          getDict("noticeProductionDepartment").then((res) => {
            state.productionDepartmentList = res;
          state.formData.productionDepartment = state.detail
            .productionDepartment
            ? state.detail.productionDepartment
            :  state.productionDepartmentList[0].value;
            console.log(state.productionDepartmentList[0],state.formData.productionDepartment,state.detail
            .productionDepartment );
            
          });
        
        }
      } else {
        state.type = "create";
        if (route.query.styleNum) {
          state.formData.styleNum = route.query.styleNum;
          productStylesChange(state.formData.styleNum);
          findProductStyles({
            styleNum: state.formData.styleNum,
          }).then((res) => {
            // state.transferOrder =
            //   res.data.reproductStyles?.transferOrderRange || [];
          });
        }
      }
    };
    // 款式发生改变时
    function productStylesChange(params) {
      getProductSpecSizeList({ styleNum: params, page: 1, pageSize: 999 }).then(
        (res) => {
          if (res.code == 0) {
            if (state.type == "create") {
              state.drawingLists = res.data.list;
              if (
                state.productStylesList.filter(
                  (item) => item.styleNum == params
                )[0]
              ) {
                state.transferOrder = state.productStylesList.filter(
                  (item) => item.styleNum == params
                )[0]?.transferOrderRange;
              }
            } else {
              getTransferOrderRange(params);
            }
            if (!route.query.ID) {
              state.drawingLists.forEach((item, index) => {
                getDdmsSpecDrawingListList({
                  sizeNum: item.sizeNum,
                  styleNum: item.styleNum,
                  page: 1,
                  pageSize: 999,
                }).then((result) => {
                  item.drawingLists = result.data.list;
                  if (
                    Array.isArray(state.detail.drawingLists) &&
                    state.detail.drawingLists.length
                  ) {
                    item.drawingList = state.detail.drawingLists.filter(
                      (it) => it.fileUrl == item.drawingList
                    )[0].drawingList;
                    item['ddmsNum'] = state.detail.drawingLists.filter(
                      (it) => it.fileUrl == item.drawingList
                    )[0].ddmsNum;
                    item['ddmsNumVersion'] = state.detail.drawingLists.filter(
                      (it) => it.fileUrl == item.drawingList
                    )[0].ddmsNumVersion;
                  } else {
                    item['drawingList'] = "";
                    item['ddmsNum'] = "";
                    item['ddmsNumVersion'] = "";
                  }
                });
              });
            }
          }
        }
      );
    }

    // 保存草稿
    function saveCaogao(params) {
      if (!state.formData.styleNum) {
        ElMessage({
          type: "warning",
          message: "请选择款式编号",
        });
        return;
      }

      if (!state.formData.customerDemandDate) {
        ElMessage({
          type: "warning",
          message: "请选择客户要求完成日期",
        });
        return;
      }

      if (!state.formData.piDemandDate) {
        ElMessage({
          type: "warning",
          message: "请选择PI要求完成日期",
        });
        return;
      }

      
     
      if (!state.allowClick) {
        return;
      } else {
        state.allowClick = false;
        setTimeout(() => {
          state.allowClick = true;
        }, 3000);
      }
      let datas = {
        ...state.formData,
        drawingLists: state.drawingLists.map((item) => {
          let val = {}
          val['drawingName'] = item.drawingLists?.filter(
            (it) => it.fileUrl == item.drawingList
          )[0]?.drawingName || '';
          val['drawingList'] = item.drawingLists?.filter(
            (it) => it.fileUrl == item.drawingList
          )[0]?.fileUrl || '';
          val['ddmsNum'] = item.drawingLists?.filter(
            (it) => it.fileUrl == item.drawingList
          )[0]?.ddmsNum || '';
          val['ddmsNumVersion'] = item.drawingLists?.filter(
            (it) => it.fileUrl == item.drawingList
          )[0]?.version || '';
          val['sizeNum'] = item.sizeNum;
          return val;
        }),
      };
      if (!datas.drawingLists.some(item=>item.drawingList)) {
        ElMessage({
          type: "warning",
          message: "请选择产品规格图",
        });
        return;
      }
      createMoldStartNotice(datas).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: "success",
            message: "创建成功",
            duration: 1000,
            onClose: () => {
              // 获取当前URL
              const currentUrl = new URL(window.location.href);
              emitter.emit("closeThisPage");
              if (window.location.href.indexOf("?") > -1) {
                window.location.href =
                  currentUrl.href +
                  "&ID=" +
                  res.data.ID +
                  "&subTitle=" +
                  res.data.noticeNum;
              } else {
                window.location.href =
                  currentUrl.href +
                  "?ID=" +
                  res.data.ID +
                  "&subTitle=" +
                  res.data.noticeNum;
              }
            },
          });
        }
      });
    }

    // 金打印啤打印
    function print(params) {
      if (params == 1) {
        setMetalSpleenPrint({
          status: 1,
          setType: "metal",
          styleNum: state.formData.styleNum,
        }).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: "success",
              message: "金打印完成",
              duration: 1000,
              onClose: () => {
                router.go(-1);
              },
            });
          }
        });
      } else if (params == 2) {
        setMetalSpleenPrint({
          status: 1,
          setType: "spleen",
          styleNum: state.formData.styleNum,
        }).then((res) => {
          if (res.code == 0) {
            ElMessage({
              type: "success",
              message: "啤打印完成",
              duration: 1000,
              onClose: () => {
                router.go(-1);
              },
            });
          }
        });
      }
    }

    function back(params) {
      router.go(-1);
    }

    function saveByRole(params) {
      if (!state.subForm.contentCate || !state.subForm.reasonCate) {
        ElMessage({
          type: "warning",
          message: "请输入内容分类和原因分离",
          duration: 1000,
        });
        return;
      }

      if (!state.allowClick) {
        return;
      } else {
        state.allowClick = false;
        setTimeout(() => {
          state.allowClick = true;
        }, 3000);
      }
      let datas = {
        ...state.formData,
        ...state.detail,
        drawingLists: state.drawingLists.map(
          ({ sizeNum, drawingList, ID, drawingName }) => ({
            sizeNum,
            drawingList,
            drawingName,
            ID,
          })
        ),
        moldStartNoticeModifyNotes: [
          {
            content: state.subForm.contentCate.join(","),
            reason: state.subForm.reasonCate.join(","),
            detail: state.subForm.remark || "",
          },
        ],
      };

      updateMoldStartNotice(datas).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: "success",
            message: "提交成功",
            duration: 1000,
            onClose: () => {
              emitter.emit("closeThisPage");
              let query = {
                styleNum: state.formData.styleNum,
                ID: route.query.ID,
              };
              query.noticeNum = state.detail.noticeNum;

              router.push({
                path: `/layout/plmMoldStartNoticeAddAndEdit`,
                query,
              });
            },
          });
        }
      });
    }

    function subAndopenDialog(params) {
      state.subDialogFormVisible = true;
    }

    // 获取款式列表
    const remoteMethodProjectStyles = async (keyword) => {
      await getProductStylesList({
        page: 1,
        pageSize: 50,
        styleNum: keyword ? keyword : undefined,
        status: 1,
        searchType: "moldStartNotice",
        // productSpecStatus: 1,
      }).then((res) => {
        if (res.code == 0) {
          state.productStylesList = res.data.list;
        }
      });
    };

    // 获取生产地列表
    const getTransferOrderRange = async (keyword) => {
      console.log(keyword);
      await getProductStylesList({
        page: 1,
        pageSize: 50,
        styleNum: keyword ? keyword : undefined,
      }).then((res) => {
        if (res.code == 0) {
          state.transferOrder = res.data.list[0].transferOrderRange;
        }
      });
    };

    // 关闭提交弹窗
    function subDialogCel(params) {
      state.subForm = {
        reasonCate: undefined,
        contentCate: undefined,
        materialNum: "",
      };
      state.subDialogFormVisible = false;
    }

    // 模具及物料清单选中
    const handleSelectionChange = (val) => {
      console.log(val);
      state.selectList = val;
    };

    // 修改状态
    function changeStatus(params) {
      let newMoldmaterialLists = JSON.parse(
        JSON.stringify(state.detail.moldmaterialLists)
      );
      if (params == "正常") {
        state.selectList.forEach((item) => {
          newMoldmaterialLists.forEach((val) => {
            val.noticeNum = state.detail.noticeNum;
            if (val.ID == item.ID) {
              val.status = "正常";
            }
          });
        });
      } else if (params == "暂停") {
        state.selectList.forEach((item) => {
          newMoldmaterialLists.forEach((val) => {
            val.noticeNum = state.detail.noticeNum;
            if (val.ID == item.ID) {
              val.status = "暂停";
            }
          });
        });
      } else if (params == "终止") {
        state.selectList.forEach((item) => {
          newMoldmaterialLists.forEach((val) => {
            val.noticeNum = state.detail.noticeNum;
            if (val.ID == item.ID) {
              val.status = "终止";
            }
          });
        });
      }
      updateMoldStartNoticeMoldmaterialList(newMoldmaterialLists).then(
        (res) => {
          if (res.code == 0) {
            ElMessage({
              type: "success",
              message: "状态修改成功",
              duration: 1000,
              onClose: () => {
                state.detail.moldmaterialLists = newMoldmaterialLists;
                state.selectList = [];
              },
            });
          }
        }
      );
    }

    function statusChange(datas, params) {
      let newMoldmaterialLists = JSON.parse(JSON.stringify(datas));
      newMoldmaterialLists.status = params;
      updateMoldStartNoticeMoldmaterialList([
        { ...newMoldmaterialLists, noticeNum: state.detail.noticeNum },
      ]).then((res) => {
        if (res.code == 0) {
          ElMessage({
            type: "success",
            message: "状态修改成功",
            duration: 1000,
            onClose: () => {
              datas.status = params;
            },
          });
        }
      });
    }
    //模房复期

    const boardMakingColumns = ref([]);
    const newBoardMakingColumns = [
      {
        prop: "ID",
        label: "序号",
        show: true,
        tableColumnProps: {
          width: "60px",
          type: "index",
        },
      },
      {
        prop: "deliveryDate",
        label: "复期日",
        show: true,
        tableColumnProps: {
          sortable: false,
          formatter: (row) => formatDate(row.deliveryDate),
        },
      },

      {
        prop: "detailDescription",
        label: "详细说明",
        show: true,
        tableColumnProps: {
          sortable: false,
        },
      },
      {
        prop: "createUser",
        label: "创建人/时间",
        show: true,
        tableColumnProps: {
          sortable: false,
          formatter: (row) => row.createUser + " " + formatDate(row.CreatedAt),
        },
      },
      {
        prop: "status",
        label: "状态",
        show: true,
        slot: "status",
        tableColumnProps: {
          sortable: false,
        },
      },

      {
        prop: "auditUser",
        label: "审核人/时间",
        show: true,
        tableColumnProps: {
          sortable: false,
          formatter: (row) => row.auditUser + " " + formatDate(row.auditDate),
        },
      },
      {
        prop: "auditDescription",
        label: "审核说明",
        show: true,
        tableColumnProps: {
          sortable: false,
        },
      },
    ];
    boardMakingColumns.value = newBoardMakingColumns;
    const boardMakingTalbeData = ref([]);
    const boardMakingForm = ref({});
    const boardMakingFormRef = ref();
    const auditBoardMakingForm = ref({});
    const auditBoardMakingFormRef = ref();
    const boardMakingVisible = ref(false);
    const auditBoardMakingVisible = ref(false);
    const changeBoardMakingVisible = (bool) => {
      boardMakingVisible.value = bool;
    };
    function addBoardMaking() {
      boardMakingForm.value = {};
      changeBoardMakingVisible(true);
    }
    function addBoardMakingSubmit() {
      boardMakingFormRef.value.validate(async (valid) => {
        if (valid) {
          const params = {
            ...boardMakingForm.value,
            noticeNum: state.detail.noticeNum,
          };
          console.log("params==============", params);
          const res = await createMoldStartNoticeMoldHouse(params);
          if (res.code === 0) {
            boardMakingForm.value = {};
            ElMessage({
              type: "success",
              message: "添加成功",
            });
            changeBoardMakingVisible(false);
            getMoldStartNoticeMoldHouseList({
              noticeNum: state.detail.noticeNum,
            }).then((res) => {
              if (res.code === 0) {
                boardMakingTalbeData.value = res.data.list;
              }
            });
          }
        }
      });
    }
    const changeAuditBoardMakingVisible = (bool) => {
      auditBoardMakingVisible.value = bool;
    };
    function auditBoardMaking(row) {
      auditBoardMakingForm.value = {
        ID: row.ID,
      };
      changeAuditBoardMakingVisible(true);
    }
    function auditBoardMakingSubmit() {
      auditBoardMakingFormRef.value.validate(async (valid) => {
        if (valid) {
          const params = {
            ...auditBoardMakingForm.value,
            noticeNum: state.detail.noticeNum,
          };
          const res = await updateMoldStartNoticeMoldHouse(params);
          if (res.code === 0) {
            auditBoardMakingForm.value = {};
            ElMessage({
              type: "success",
              message: "审核成功",
            });
            changeAuditBoardMakingVisible(false);
            getMoldStartNoticeMoldHouseList({
              noticeNum: state.detail.noticeNum,
            }).then((res) => {
              if (res.code === 0) {
                boardMakingTalbeData.value = res.data.list;
              }
            });
          }
        }
      });
    }

    // 款式查询弹窗
    // 打开 新增、编辑
    const openCreateAndEdit = () => {
      state.editReasonDialogShow = true;
    };

    // 关闭款式查询弹窗
    function closeDialog(params) {
      state.editReasonDialogShow = false;
    }

    function selectStyleNum(params) {
      state.formData.styleNum = params.styleNum;
      productStylesChange(params.styleNum);
      state.editReasonDialogShow = false;
    }

    // 打印预览
    function preview(params) {
      state.previewDialogShow = true;
    }

    function closePreview(params) {
      state.previewDialogShow = false;
    }

    function printNotice(params) {
      const style = "@page {margin:0mm 10mm};"; //打印时去掉眉页眉尾
      printJS({
        printable: "myPrint", // 标签元素id
        type: "html",
        font_size: "12px", // 不设置则使用默认字体大小
        header: "",
        targetStyles: ["*"],
        style,
      });
    }
    // 下载
    const downloadFile = (row) => {
      let params = {
          drawingName: row.drawingName,
          fileUrl: row.drawingList,
      };
      downloadFilePost(params).then((data) => {
        if (data.response && data.response.status == 404) {
            ElMessage({
                type: "warning",
                message: "文件不存在",
            });
            return;
        }
        let blob = new Blob([data.data], {});
        const fileName = row.drawingName;
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link); // 下载完成移除元素
        window.URL.revokeObjectURL(url); // 释放掉blob对象
    });
      // let name =
      //   row.drawingList.split("/")[row.drawingList.split("/").length - 1];
      // const path = ref(import.meta.env.VITE_BASE_PATH + "/");
      // let fileUrl;
      // if (
      //   row.drawingList.indexOf("http://") > -1 ||
      //   row.drawingList.indexOf("https://") > -1
      // ) {
      //   fileUrl = row.drawingList.replace(new RegExp("#", "g"), "");
      // } else {
      //   fileUrl =
      //     path.value + row.drawingList.replace(new RegExp("#", "g"), "");
      // }
      // const x = new XMLHttpRequest();
      // x.open("GET", fileUrl, true);
      // x.responseType = "blob";
      // x.onload = (e) => {
      //   // 会创建一个 DOMString，其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。
      //   const url = window.URL.createObjectURL(x.response);
      //   const a = document.createElement("a");
      //   a.href = url;
      //   a.download = name;
      //   a.click();
      // };
      // x.send();
    };

    function productionDepartmentChange(params) {
      updateMoldStartNoticeDepartment({
        noticeNum: state.detail.noticeNum,
        productionDepartment: params,
      }).then((res) => {
        if (res.code === 0) {
          ElMessage({
            type: "success",
            message: "修改制作部门成功",
          });
        }
      });
    }

    onMounted(() => {
      init();
    });

    return {
      ...toRefs(state),
      route,
      productStylesChange,
      back,
      saveCaogao,
      saveByRole,
      subAndopenDialog,
      print,
      remoteMethodProjectStyles,
      formatDate,
      subDialogCel,
      handleSelectionChange,
      changeStatus,
      statusChange,
      path1,
      xToken,
      // 模房复期
      boardMakingColumns,
      boardMakingTalbeData,
      addBoardMaking,
      addBoardMakingSubmit,
      boardMakingForm,
      boardMakingFormRef,
      auditBoardMakingForm,
      auditBoardMakingFormRef,
      boardMakingVisible,
      auditBoardMakingVisible,
      auditBoardMaking,
      auditBoardMakingSubmit,
      openCreateAndEdit,
      closeDialog,
      selectStyleNum,
      preview,
      closePreview,
      dayjs,
      printNotice,
      downloadFile,
      productionDepartmentChange,
      btnAuth,
      userStore,
    };
  },
};
</script>

<style lang="scss" scoped>
.form-header {
  font-size: 22px;
  font-weight: 600;
  background: #fff;
  padding: 20px;
  border-bottom: 1px solid #ccc5;
}

.form-box {
  margin: 0 auto;
}

.form-footer {
  text-align: center;
  margin-top: 20px;
}

.table-form {
  margin-bottom: 40px;

  .el-form-item {
    margin-bottom: 0;
    width: 80%;
  }

  .table-title {
    margin-bottom: 20px;
    margin-top: 20px;
    font-size: 16px;
    font-weight: bold;
    line-height: 16px;
  }
}
</style>
<style lang="scss" scoped>
@import url("@/style/common/common.scss");

:deep(.el-descriptions__label) {
  min-width: 100px !important;
}

:deep(.el-descriptions__cell) {
  min-width: 100px !important;

  .el-date-editor.el-input,
  .el-date-editor.el-input__wrapper {
    width: unset;
    min-width: 120px;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-box {
  display: flex;
  align-items: center;

  .title {
    font-size: 20px;
    font-weight: 600;
    margin-right: 8px;
  }
}

.preview-box {
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: 10;
  background-color: #fff;
  padding: 20px;
  overflow: auto;
  .one-box {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
    > div {
      font-size: 16px !important;
      text-align: left;
      width: 33.33%;
      &:last-child {
        margin-top: 10px;
        text-align: right;
      }
    }

    padding-bottom: 30px;
    border-bottom: 2px solid rgb(240, 240, 240);
  }

  .content-box {
    margin-top: 30px;
    .title {
      margin-bottom: 20px;
      font-size: 14px;
    }

    .content {
      border-top: 2px solid rgb(240, 240, 240);
      border-bottom: 2px solid rgb(240, 240, 240);
      padding: 20px 0 0px;

      :deep(.el-descriptions__label) {
        margin-right: 6px;
      }

      .myTable-head {
        display: flex;
        justify-content: space-around;
        text-align: left;

        font-weight: bold;
        padding-bottom: 4px;
        > div {
          flex: 1;
          font-size: 12px !important;
        }

        border-bottom: 4px solid rgb(240, 240, 240);
      }
      .myTable-content {
        display: flex;
        justify-content: space-around;
        text-align: left;
        margin-top: 4px;
        padding-bottom: 4px;
        > div {
          flex: 1;
          font-size: 12px !important;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        border-bottom: 1px solid rgb(240, 240, 240);
        &:last-child {
          border-bottom: 0px solid rgb(240, 240, 240);
        }
      }
    }

    :deep(.is-leaf) {
      background-color: unset !important;
    }

    :deep(
        .el-descriptions__body .el-descriptions__table .el-descriptions__cell
      ) {
      font-size: 12px;
    }
  }
}
</style>
